/**
 * Lazy Loading Images Script
 * 图片懒加载脚本
 * 
 * @package WP Bootstrap Woo
 */

(function() {
    'use strict';

    const WBW_LazyLoad = {
        options: {
            threshold: 0.1,
            rootMargin: '50px 0px',
            loadingClass: 'lazy-loading',
            loadedClass: 'lazy-loaded',
            errorClass: 'lazy-error'
        },

        init: function() {
            // 检查浏览器支持
            if (!('IntersectionObserver' in window)) {
                this.fallbackLoad();
                return;
            }

            this.setupObserver();
            this.setupImages();
            this.setupBackgrounds();
        },

        setupObserver: function() {
            this.observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        this.loadElement(entry.target);
                        this.observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: this.options.threshold,
                rootMargin: this.options.rootMargin
            });
        },

        setupImages: function() {
            // 查找所有需要懒加载的图片
            const lazyImages = document.querySelectorAll('img[data-src]');
            
            lazyImages.forEach(img => {
                // 添加loading类
                img.classList.add(this.options.loadingClass);
                
                // 设置占位符
                if (!img.src) {
                    img.src = this.createPlaceholder(img);
                }
                
                // 开始观察
                this.observer.observe(img);
            });
        },

        setupBackgrounds: function() {
            // 查找所有需要懒加载的背景图片
            const lazyBackgrounds = document.querySelectorAll('[data-bg]');
            
            lazyBackgrounds.forEach(element => {
                element.classList.add(this.options.loadingClass);
                this.observer.observe(element);
            });
        },

        loadElement: function(element) {
            if (element.tagName === 'IMG') {
                this.loadImage(element);
            } else if (element.dataset.bg) {
                this.loadBackground(element);
            }
        },

        loadImage: function(img) {
            const src = img.dataset.src;
            const srcset = img.dataset.srcset;
            
            if (!src) return;

            // 创建新图片对象预加载
            const imageLoader = new Image();
            
            imageLoader.onload = () => {
                // 加载成功
                img.src = src;
                if (srcset) {
                    img.srcset = srcset;
                }
                
                img.classList.remove(this.options.loadingClass);
                img.classList.add(this.options.loadedClass);
                
                // 移除data属性
                delete img.dataset.src;
                if (srcset) delete img.dataset.srcset;
                
                // 触发自定义事件
                this.dispatchEvent(img, 'lazyloaded');
            };
            
            imageLoader.onerror = () => {
                // 加载失败
                img.classList.remove(this.options.loadingClass);
                img.classList.add(this.options.errorClass);
                
                // 设置错误图片
                img.src = this.getErrorImage();
                
                this.dispatchEvent(img, 'lazyerror');
            };
            
            // 开始加载
            imageLoader.src = src;
        },

        loadBackground: function(element) {
            const bg = element.dataset.bg;
            
            if (!bg) return;

            // 创建新图片对象预加载
            const imageLoader = new Image();
            
            imageLoader.onload = () => {
                // 加载成功
                element.style.backgroundImage = `url(${bg})`;
                
                element.classList.remove(this.options.loadingClass);
                element.classList.add(this.options.loadedClass);
                
                // 移除data属性
                delete element.dataset.bg;
                
                this.dispatchEvent(element, 'lazyloaded');
            };
            
            imageLoader.onerror = () => {
                // 加载失败
                element.classList.remove(this.options.loadingClass);
                element.classList.add(this.options.errorClass);
                
                this.dispatchEvent(element, 'lazyerror');
            };
            
            // 开始加载
            imageLoader.src = bg;
        },

        createPlaceholder: function(img) {
            // 获取图片尺寸
            const width = img.dataset.width || img.getAttribute('width') || 300;
            const height = img.dataset.height || img.getAttribute('height') || 200;
            
            // 创建SVG占位符
            const svg = `
                <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
                    <rect width="100%" height="100%" fill="#f0f0f0"/>
                    <text x="50%" y="50%" text-anchor="middle" dy=".3em" fill="#999" font-family="Arial, sans-serif" font-size="14">
                        Loading...
                    </text>
                </svg>
            `;
            
            return 'data:image/svg+xml;base64,' + btoa(svg);
        },

        getErrorImage: function() {
            // 错误图片SVG
            const errorSvg = `
                <svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
                    <rect width="100%" height="100%" fill="#f8f8f8"/>
                    <text x="50%" y="50%" text-anchor="middle" dy=".3em" fill="#ccc" font-family="Arial, sans-serif" font-size="14">
                        Image not found
                    </text>
                </svg>
            `;
            
            return 'data:image/svg+xml;base64,' + btoa(errorSvg);
        },

        dispatchEvent: function(element, eventName) {
            const event = new CustomEvent(eventName, {
                bubbles: true,
                detail: { element }
            });
            element.dispatchEvent(event);
        },

        // 降级处理（不支持IntersectionObserver的浏览器）
        fallbackLoad: function() {
            const lazyImages = document.querySelectorAll('img[data-src]');
            const lazyBackgrounds = document.querySelectorAll('[data-bg]');
            
            // 立即加载所有图片
            lazyImages.forEach(img => {
                if (img.dataset.src) {
                    img.src = img.dataset.src;
                    if (img.dataset.srcset) {
                        img.srcset = img.dataset.srcset;
                    }
                    img.classList.add(this.options.loadedClass);
                }
            });
            
            lazyBackgrounds.forEach(element => {
                if (element.dataset.bg) {
                    element.style.backgroundImage = `url(${element.dataset.bg})`;
                    element.classList.add(this.options.loadedClass);
                }
            });
        },

        // 手动刷新（用于动态添加的内容）
        refresh: function() {
            this.setupImages();
            this.setupBackgrounds();
        },

        // 销毁观察器
        destroy: function() {
            if (this.observer) {
                this.observer.disconnect();
            }
        }
    };

    // 自动初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            WBW_LazyLoad.init();
        });
    } else {
        WBW_LazyLoad.init();
    }

    // 全局暴露
    window.WBW_LazyLoad = WBW_LazyLoad;

    // 为图片添加懒加载属性的辅助函数
    window.WBW_MakeLazy = function(selector) {
        const images = document.querySelectorAll(selector || 'img');
        
        images.forEach(img => {
            if (img.src && !img.dataset.src) {
                img.dataset.src = img.src;
                img.src = WBW_LazyLoad.createPlaceholder(img);
                WBW_LazyLoad.observer.observe(img);
            }
        });
    };

})();

// CSS样式（通过JavaScript注入）
const lazyLoadStyles = `
    .lazy-loading {
        opacity: 0.5;
        transition: opacity 0.3s ease;
    }

    .lazy-loaded {
        opacity: 1;
        animation: fadeIn 0.3s ease;
    }

    .lazy-error {
        opacity: 0.3;
        filter: grayscale(100%);
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    /* 加载动画效果 */
    .lazy-loading::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
        animation: shimmer 1.5s infinite;
    }

    @keyframes shimmer {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
    }
`;

// 注入CSS样式
if (!document.getElementById('lazy-load-styles')) {
    const styleSheet = document.createElement('style');
    styleSheet.id = 'lazy-load-styles';
    styleSheet.textContent = lazyLoadStyles;
    document.head.appendChild(styleSheet);
}